package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

// 读文件
func main1() {
	// filename := "./test.txt"
	filename := "/Users/xiaojg/git/gitee/goclean/gobase/w8-10-generic-time-fileio/3file/test.txt"
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	defer f.Close()

	fmt.Printf("%T  %+[1]v\n", f)
	// 读
	buffer := make([]byte, 2)
	for {
		n, err := f.Read(buffer)
		if err != nil {
			fmt.Println(err, n, "$$$$")
			break
		} else {
			fmt.Println(buffer, n, buffer[:n], string(buffer[:n]))
		}
	}
	fmt.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
	n, err := f.Read(buffer)
	fmt.Println(n, err)

}

// 读写文件的句柄指针操作，Seek
func main2() {
	filename := "/Users/xiaojg/git/gitee/goclean/gobase/w8-10-generic-time-fileio/3file/test.txt"
	if f, err := os.Open(filename); err == nil {
		defer f.Close()
		buffer := make([]byte, 5)
		var n int
		n, _ = f.ReadAt(buffer, 3)
		fmt.Println(n, f.Fd(), f.Name())
		fmt.Println(buffer, len(buffer), cap(buffer), string(buffer[:n]))

		// 3次读操作
		n, _ = f.Read(buffer)
		fmt.Println(n, f.Fd(), f.Name())
		fmt.Println(buffer, len(buffer), cap(buffer), string(buffer[:n]))

		n, _ = f.Read(buffer)
		fmt.Println(n, f.Fd(), f.Name())
		fmt.Println(buffer, len(buffer), cap(buffer), string(buffer[:n]))

		n, _ = f.Read(buffer)
		fmt.Println(n, f.Fd(), f.Name())
		fmt.Println(buffer, len(buffer), cap(buffer), string(buffer[:n]))

		off, e := f.Seek(0, 1) //通过修改参数，看到不同的效果
		if e == nil {
			fmt.Println(off, "@@@")
			buffer = make([]byte, 5)
			n, _ = f.Read(buffer)
			fmt.Println(n, buffer)
		} else {
			fmt.Println(e)
		}
	}
}

// 带缓存读取
func main() {
	filename := "/Users/xiaojg/git/gitee/goclean/gobase/w8-10-generic-time-fileio/3file/test.txt"

	if f, err := os.Open(filename); err != nil {
		panic(err)
	} else {
		defer f.Close()
		reader := bufio.NewReader(f)
		b1, err := reader.ReadBytes('1')
		fmt.Println("01: ", string(b1), err)
		b2 := make([]byte, 3)
		n, err := reader.Read(b2)
		fmt.Println("02: ", n, b2, string(b2[:n]), err)
		b3, err := reader.ReadBytes('\n')
		fmt.Println("03: ", b3, string(b3), err)

		b4, err := reader.ReadSlice('\n')
		fmt.Println("04: ", b4, string(b4), err)

		b5, err := reader.ReadString('\n')
		fmt.Println("05: ", b5, err)
		fmt.Println(strings.TrimRight(b5, "\n"))

		rline, size, err := reader.ReadRune()
		fmt.Println("readrune: ", rline, string(rline), size, err)

		line, tag, err := reader.ReadLine()
		fmt.Println("readline: ", line, string(line), tag, err)

		if err == io.EOF {
			f.Seek(0, 0)
		}

	}

}
